package com.yeqian.system.service.Impl;


import com.yeqian.system.entity.SystemConfig;
import com.yeqian.system.job.LogJob;
import com.yeqian.system.mapper.SystemConfigMapper;
import com.yeqian.system.service.TaskTimeService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

@Slf4j
@Service
public class TaskTimeServiceImpl implements TaskTimeService, CommandLineRunner {

    @Resource
    private Scheduler scheduler;

    @Resource
    private SystemConfigMapper systemConfigMapper;

    /**
     * 启动定时任务
     *
     * @param systemConfig
     * @throws Exception
     */
    public void startQuartz(SystemConfig systemConfig) {

        /**通过JobBuilder.newJob()方法获取到当前Job的具体实现(以下均为链式调用)
         * 这里是固定Job创建，所以代码写死XXX.class
         * 如果是动态的，根据不同的类来创建Job，则 ((Job)Class.forName("com.zy.job.TestJob").newInstance()).getClass()
         * 即是 JobBuilder.newJob(((Job)Class.forName("com.zy.job.TestJob").newInstance()).getClass())
         * */
        String recordid = systemConfig.getId();
        JobDetail jobDetail = JobBuilder.newJob(LogJob.class)
                /**给当前JobDetail添加参数，K V形式，链式调用，可以传入多个参数，在Job实现类中，
                 * 可以通过jobExecutionContext.getJobDetail().getJobDataMap().get("age")获取值*/
//                .usingJobData("recordid", recordid)
                /**添加认证信息，有3种重写的方法，我这里是其中一种，可以查看源码看其余2种*/
                .withIdentity(recordid)
                .build();

        Optional.ofNullable(systemConfig.getCaonfigValue()).ifPresent(configValue -> {
            try {
                CronTrigger trigger = TriggerBuilder.newTrigger()
                        .withIdentity(recordid)
                        /**立即生效*/
                        .startNow()
                        /**添加执行规则，SimpleTrigger、CronTrigger的区别主要就在这里,我这里是demo，写了个每2分钟执行一次*/
                        .withSchedule(CronScheduleBuilder.cronSchedule(configValue))
                        .build();
                scheduler.scheduleJob(jobDetail, trigger);
                if (!scheduler.isShutdown()) {
                    scheduler.start();
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        });

        log.info("--------定时任务启动成功 " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " ------------");
    }

    /**
     * 删除定时任务
     *
     * @param systemConfig
     */
    public void deleteQuartz(SystemConfig systemConfig) {
        String recordid = systemConfig.getId();
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(recordid);
            //暂停触发器
            scheduler.pauseTrigger(triggerKey);
            //移除触发器
            scheduler.unscheduleJob(triggerKey);
            //删除Job
            scheduler.deleteJob(JobKey.jobKey(recordid));
        } catch (Exception e) {
            log.error("deleteTodoConfigQuartz is error,e={} ,recordid={}", e.getMessage(), recordid);
        }

        log.info("--------定时任务关闭成功 " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " ------------");
    }

    // 项目启动自动执行，每月清理一次日志，只保留最近一个月内的日志
    @Override
    public void run(String... args) throws Exception {
        this.startQuartz(systemConfigMapper.selectById("bd192005-dbd7-11ec-bc2a-00ff3acdb0bc"));
    }
}
